from PyQt5.QtCore import Qt
from qgis._core import QgsPointXY, QgsFeature, QgsGeometry
from qgis._gui import QgsMapTool


class RouteMapTool(QgsMapTool):
    # 自定义地图工具用于绘制航线
    def __init__(self, canvas, route_layer, main_window):
        super().__init__(canvas)
        self.canvas = canvas
        self.route_layer = route_layer
        self.main_window = main_window
        self.points = []

        # 设置光标样式
        self.setCursor(Qt.CrossCursor)

    def canvasPressEvent(self, event):
        # 处理画布点击事件
        # 右键点击退出绘制模式
        if event.button() == Qt.RightButton:
            self.main_window.exit_drawing()
            return

        # 左键点击添加航点
        if event.button() == Qt.LeftButton:
            point = self.toMapCoordinates(event.pos())
            self.points.append(QgsPointXY(point.x(), point.y()))
            print(f"添加航点: ({point.x():.6f}, {point.y():.6f})")

            # 如果有两个或更多点，创建线段
            if len(self.points) >= 2:
                self.update_route()

    def update_route(self):
        """更新航线图层"""
        # 创建线要素
        feature = QgsFeature()
        feature.setGeometry(QgsGeometry.fromPolylineXY(self.points))

        # 添加到图层
        provider = self.route_layer.dataProvider()
        provider.addFeatures([feature])
        self.route_layer.triggerRepaint()

        # 缩放到新添加的要素
        self.canvas.zoomToFeatureExtent(feature.geometry().boundingBox())

    def deactivate(self):
        """工具停用时清空点列表"""
        self.points = []
        super().deactivate()